#pragma once
#include <iostream>
#include "Log.hpp"
#include "InetAddr.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cerrno>
#include <string.h>
#include <unistd.h>
#include <vector>

enum Error
{
    SOCKET_ERROR = 1,
    BIND_ERROR
};

static const int defaultfd = -1;

class UdpServer
{
public:
    UdpServer(uint16_t port):_sockfd(defaultfd), _port(port), _is_running(false)
    {
        _initServer();
    }
    ~UdpServer()
    {}
private:
    void _initServer()
    {
        // 1.create the udp socket
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            Log(FATAL, "Server init socket error: %s", strerror(errno));
            exit(SOCKET_ERROR);
        }
        Log(INFO, "Server init socket success !");

        // 2.create a sockaddr_in type variable, meanwhile set its public mumber
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        // set sin_addr : 
        // <1> convert the host sequence into a network sequence
        // <2> IP address in string style in dotted decimal
        // inet_addr(const char* ip) converts the Internet host address cp from IPv4 numbers-and-dots notation into binary data in network byte order
        // local.sin_addr = inet_addr(ip);
        local.sin_addr.s_addr = INADDR_ANY;     // allow the any ip to access the _port

        // 3.bind the sockfd and network message(sockaddr_in variable)
        int n = bind(_sockfd, reinterpret_cast<sockaddr*>(&local), sizeof(local));
        if(n < 0)
        {
            Log(FATAL, "Server init bind error: %s", strerror(errno));
            exit(BIND_ERROR);
        }
        Log(INFO, "Server init bind success !");
    }

    void _addOnlineUser(InetAddr addr)
    {
        pthread_mutex_lock(&_user_mutex);
        for (auto &user : _online_user)
        {
            if (addr == user)
            {
                pthread_mutex_unlock(&_user_mutex);
                return;
            }
        }
        _online_user.push_back(addr);
        pthread_mutex_unlock(&_user_mutex);

        Log(INFO, "%s:%d is added to online user list...", addr.IP().c_str(), addr.port());
    }
public:
    void start()
    {
        _is_running = true;

        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        while(true)
        {
            // 1.receive the message from client by recvfrom()
            int n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1,
                             0, reinterpret_cast<sockaddr*>(&peer), &len);
            if(n > 0)
            {
                buffer[n] = 0;
                InetAddr addr(peer);
                _addOnlineUser(addr);
                std::cout << "server receive message: " << buffer << std::endl;
                Log(INFO, "get message-{%s}-from [%s, %d]", buffer, addr.IP().c_str(), addr.port());  // log the message into file

                // 2.send the message back to client by send()
                pthread_mutex_lock(&_user_mutex);
                for(auto user : _online_user)
                {
                    sendto(_sockfd, buffer, sizeof(buffer), 0,
                        reinterpret_cast<sockaddr*>(const_cast<sockaddr_in*>(&(user.addr()))), len);
                    printf("server send message to %s:%d\n", user.IP().c_str(), user.port());
                }
                pthread_mutex_unlock(&_user_mutex);
            }
            sleep(1);
        }

        _is_running = false;
    }

private:
    std::vector<InetAddr> _online_user;
    pthread_mutex_t _user_mutex;

    int _sockfd;
    uint16_t _port;     // the port number of server
    bool _is_running;
};
